package br.os.xml;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;

import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import br.os.model.Message;
import br.os.model.Ordem;
/**
 * XMLConvert
 */
public class XMLConvert {
	/**
	 * XMLtoObject
	 */
	public static Vector XMLtoObject(InputStream in) {
		Vector vector = new Vector();
		Message message;
		try {
			if ((in != null) && (in.available() > 0)) {
				KXmlParser parser = new KXmlParser();
				parser.setInput(new InputStreamReader(in));
				parser.nextTag();
				parser.require(XmlPullParser.START_TAG, null, "operacao");
				String id = parser.getAttributeValue(0);
				if (id != null) {
				  // Resposta do Login ou Baixa de OS
					if (id.equals("0") || id.equals("2")) { 
						parser.nextTag();
						parser.require(XmlPullParser.START_TAG, null, "message");
						message = new Message();
						message.setCode(parser.getAttributeValue(0));
						message.setMensagem(parser.nextText());
						vector.addElement(message);
						parser.require(XmlPullParser.END_TAG, null, "message");
						parser.nextTag();
					} else if (id.equals("1")) { // Resposta da Consulta
						parser.nextTag();
						parser.require(XmlPullParser.START_TAG, null, "ordens");
						int Quantidade = Integer.parseInt(parser.getAttributeValue(0));
						parser.nextTag();
						for (int i = 0; i < Quantidade; i++) {
							parser.require(XmlPullParser.START_TAG, null, "ordem");
							Ordem ordem = new Ordem();
							ordem.setId(Integer.parseInt(parser.getAttributeValue(0)));
							ordem.setCliente(parser.getAttributeValue(1));
							ordem.setServico(parser.nextText());
							vector.addElement(ordem);
							parser.require(XmlPullParser.END_TAG, null, "ordem");
							parser.nextTag();
						}
						parser.require(XmlPullParser.END_TAG, null, "ordens");
						parser.nextTag();
					}
				}
				parser.require(XmlPullParser.END_TAG, null, "operacao");
			}
		} catch (NumberFormatException e) {
			vector.removeAllElements();
			message = new Message();
			message.setCode("-2");
			message.setMensagem("Problema na Resposta");
			vector.addElement(message);
		} catch (IOException e) {
			vector.removeAllElements();
			message = new Message();
			message.setCode("-3");
			message.setMensagem("Problema na Resposta");
			vector.addElement(message);
		} catch (XmlPullParserException e) {
			vector.removeAllElements();
			message = new Message();
			message.setCode("-1");
			message.setMensagem("Problema na Resposta");
			vector.addElement(message);
		}
		return vector;
	}
}
